'use strict';

const Controller = require('egg').Controller;

class TagController extends Controller {
  // 获取标签列表
  async index() {
    const { ctx, service } = this;

    try {
      const { page = 1, pageSize = 20, type, keyword } = ctx.query;

      const result = await service.tag.getList({
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        type,
        keyword
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取标签详情
  async show() {
    const { ctx, service } = this;

    try {
      const { id } = ctx.params;
      const tag = await service.tag.getById(id);

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: tag,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 创建标签
  async create() {
    const { ctx, service } = this;

    try {
      const tag = await service.tag.create(ctx.request.body);

      ctx.body = {
        code: 200,
        message: '创建成功',
        data: tag,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新标签
  async update() {
    const { ctx, service } = this;

    try {
      const { id } = ctx.params;
      const tag = await service.tag.update(id, ctx.request.body);

      ctx.body = {
        code: 200,
        message: '更新成功',
        data: tag,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 删除标签
  async destroy() {
    const { ctx, service } = this;

    try {
      const { id } = ctx.params;
      await service.tag.delete(id);

      ctx.body = {
        code: 200,
        message: '删除成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取所有启用的标签
  async active() {
    const { ctx, service } = this;

    try {
      const tags = await service.tag.getAllActive();

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: tags,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 根据类型获取标签
  async byType() {
    const { ctx, service } = this;

    try {
      const { type } = ctx.params;
      const tags = await service.tag.getByType(type);

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: tags,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = TagController;
